import { defineStore } from "pinia";
import {
  getPositionList, //获取库位列表
  goodsListPage, // 物资管理分页
  AddPut, // 入库单新增
  UpdatePut, // 入库单修改
  getPutDetail, //入库单查询详情
  submitPut, //入库单提交
  saveBatchPutGoods, //批量添加入库单物资
  getAddGoodsList, //入库单物资列表
} from "@/utils/api/InventoryManagement/InventoryManagement";
import { dictlist } from "@/utils/api/dict/dict"; //字典列表
import { useMemberStore } from "@/stores/modules/member";
import { useToastStore } from "@/stores/modules/toast";
//新增列表头
const addListHeader = [
  "物资名称",
  "单位",
  "批次",
  "有效期",
  "库位",
  "数量",
  "操作",
];
//物资列表头
const goodsListHeader = ["物资名称", "物资类型", "单位"];
export const useIMputOtherStore = defineStore(
  "IMputOther",
  () => {
    const memberStore = useMemberStore();
    const toastStore = useToastStore();
    const PutCode: any = ref(""); //入库单号
    const addOrdetailOrEdit = ref("add"); //新增、详情、编辑
    // 新增入库单物资表头
    const addtableHeader = addListHeader;
    // 物资表头
    const goodsTableHeader = goodsListHeader;
    //库位列表
    const KWlist: any = [];
    const positionList = reactive({ KWlist });
    // 获取库位列表
    const getPositionListData = async () => {
      const res = await getPositionList({
        GodownCode: memberStore.GodownCode,
      });
      positionList.KWlist = res.data;
    };
    // 入库类型列表
    let TypeList: any = [];
    let putTypeList: any = reactive({ TypeList });
    //获取类型列表
    const getGoodsTypeList = async () => {
      const res = await dictlist({
        DictStatus: "Normal",
        DictType: "PutType",
      });
      const arr = res.data.map((item: any) => {
        return {
          text: item.DictName,
          value: item.DictCode,
        };
      });
      putTypeList.TypeList = arr;
    };
    /*******************物资**********************/
    // 选择的物资列表
    let selectGoods: any = [];
    let selectGoodsList: any = reactive({ selectGoods });
    // 选择的物资项
    let selectItemList: any = [];
    let selectItemObj: any = reactive({ selectItemList });
    //确定的物资列表
    let DefiniteMaterialList: any = [];
    let CodeS: any = [];
    let DefiniteMaterial: any = reactive({ DefiniteMaterialList, CodeS });
    //全选状态
    let allchecked = ref(false);
    //存在选中项
    let exist_checked = ref(false);
    // 物资列表分页
    const goodsList: any = [];
    const goodsListData = reactive({
      goodsList,
      total: 0,
      currPage: 1,
      totalPage: 1,
    });
    // 获取物资列表分页
    const getGoodsListData = async (data: any) => {
      const res: any = await goodsListPage({
        GoodsStatus: "Normal",
        pageNum: data.pageNum || 1,
        pageSize: data.pageSize || 10,
        searchParam: data.searchParam,
      });
      res.data?.list.forEach((item: any) => {
        item.checked = false;
      });

      exist_checked.value = false;
      allchecked.value = false;

      goodsListData.total = res.data.totalCount;

      if (data.Scroll) {
        //滚动加载
        goodsListData.goodsList.push(...res.data.list);
        if (
          selectGoodsList.selectGoods.length < goodsListData.goodsList.length &&
          selectGoodsList.selectGoods.length > 0
        ) {
          exist_checked.value = true;
          allchecked.value = false;
        }
      } else {
        //搜索或初次加载
        goodsListData.goodsList = res.data.list;
        exist_checked.value = false;
        allchecked.value = false;
        //初始化物资列表
        selectGoodsList.selectGoods = [];
        selectItemObj.selectItemList = [];
      }

      goodsListData.currPage = res.data.currPage;
      goodsListData.totalPage = res.data.totalPage;
    };
    //选择全部
    const selectAll = () => {
      let arr: any = [];
      let arrObj: any = [];
      if (
        selectGoodsList.selectGoods.length == goodsListData.goodsList.length
      ) {
        //取消全选
        exist_checked.value = false;
        allchecked.value = false;
        goodsListData.goodsList.forEach((item: any) => {
          item.checked = false;
        });
        selectGoodsList.selectGoods = [];
        selectItemObj.selectItemList = [];
      } else {
        goodsListData.goodsList.forEach((item: any) => {
          item.checked = true;
          arr.push(item.GoodsCode);
          arrObj.push(item);
        });
        selectGoodsList.selectGoods = arr;
        selectItemObj.selectItemList = arrObj;
        allchecked.value = true;
        exist_checked.value = false;
      }
      console.log(
        "全选",
        selectGoodsList.selectGoods,
        selectItemObj.selectItemList
      );
    };
    //选中单个
    const selectItem = (data: any) => {
      if (data.checked) {
        //单个选中code
        selectGoodsList.selectGoods.push(data.GoodsCode);
        //单个选中对象
        selectItemObj.selectItemList.push(data);
        if (
          selectGoodsList.selectGoods.length == goodsListData.goodsList.length
        ) {
          exist_checked.value = false;
          allchecked.value = true;
        } else {
          exist_checked.value = true;
          allchecked.value = false;
        }
        console.log(
          "选择",
          selectGoodsList.selectGoods,
          selectItemObj.selectItemList
        );
      } else {
        allchecked.value = false;
        exist_checked.value = true;
        const index = selectGoodsList.selectGoods.indexOf(data.GoodsCode);
        selectGoodsList.selectGoods.splice(index, 1);
        selectItemObj.selectItemList.splice(index, 1);
        if (selectGoodsList.selectGoods.length == 0) {
          exist_checked.value = false;
          allchecked.value = false;
        }
        console.log(
          "取消选择",
          selectGoodsList.selectGoods,
          selectItemObj.selectItemList
        );
      }
    };
    //确定添加物资
    const addGoods = async () => {
      DefiniteMaterial.CodeS = selectGoodsList.selectGoods; //确定物资code
      DefiniteMaterial.DefiniteMaterialList = selectItemObj.selectItemList; //确定物资项
      if (DefiniteMaterial.CodeS.length == 0) {
        return;
      }
      const data = handleAddGoodsData(DefiniteMaterial.DefiniteMaterialList);
      console.log("确定物资", data);

      await saveBatchPutGoods(data);
      //刷新新增物资信息列表
      await getAddGoods({ searchParam: "", pageNum: 1, pageSize: 10 });
      //清空选择项
      setTimeout(() => {
        selectItemObj.selectItemList = [];
        selectGoodsList.selectGoods = [];
      }, 500);
    };
    //处理添加物资数据
    const handleAddGoodsData = (Obj: any) => {
      let goods: any = Obj;
      let put_goods: any = [];
      let data: any = { goods: [] };
      for (var i = 0; i < goods.length; i++) {
        if (goods[i].UUUU == "" || goods[i].UUUU == null) {
          put_goods.push({
            PutCode: PutCode.value,
            ExpirationDates: null,
            SpecsNumber: null,
            GoodsCode: goods[i].GoodsCode,
            SpecsUnit: goods[i].SpecsCode,
            GoodsBatch: null,
            BoxCode: memberStore.GodownCode,
            BigPackingUnits: null,
            MiddlePackingUnits: null,
          });
        } else if (goods[i].UUUU == goods[i].BigPackingUnits) {
          put_goods.push({
            PutCode: PutCode.value,
            ExpirationDates: null,
            SpecsNumber: null,
            GoodsCode: goods[i].GoodsCode,
            SpecsUnit: goods[i].SpecsCode,
            GoodsBatch: null,
            BoxCode: memberStore.GodownCode,
            BigPackingUnits: goods[i].UUUU,
            MiddlePackingUnits: null,
          });
        } else if (goods[i].UUUU == goods[i].MiddlePackingUnits) {
          put_goods.push({
            PutCode: PutCode.value,
            ExpirationDates: null,
            SpecsNumber: null,
            GoodsCode: goods[i].GoodsCode,
            SpecsUnit: goods[i].SpecsCode,
            GoodsBatch: null,
            BoxCode: memberStore.GodownCode,
            BigPackingUnits: null,
            MiddlePackingUnits: goods[i].UUUU,
          });
        }
      }
      data.goods = put_goods;
      return data;
    };
    /******************************入库单***********************/
    //清空数据
    const clearData = () => {
      PutCode.value = "";
      addOrdetailOrEdit.value = "add";
      selectGoodsList.selectGoods = [];
      selectItemObj.selectItemList = [];
      DefiniteMaterial.CodeS = [];
      DefiniteMaterial.DefiniteMaterialList = [];
      deleteGoodsList.delCodes = [];
      addGoodsInfoList.addGoodsList = [];
      putOderDetail.putDetail = {};
    };
    // 新增物资信息列表
    const addGoodsList: any = [];
    const addGoodsInfoList: any = reactive({
      addGoodsList,
      currPage: 1,
      totalPage: 0,
    });
    // 新增入库单
    const addPutOrder = async (data: any) => {
      const res: any = await AddPut({
        GodownCode: memberStore.GodownCode,
        PutType: data.PutType,
        PutTime: data.PutDate || "",
        PutRemarks: data.PutRemarks || "",
        Operator: memberStore.user_id,
      });
      PutCode.value = res.data.PutCode;
      toastStore.show = true;
      toastStore.title = "保存成功！";
      toastStore.type = "success";
      console.log("新增入库单", res, PutCode.value);

      addOrdetailOrEdit.value = "edit";
    };
    //编辑入库单
    const updatePutOrder = async (data: any) => {
      if (isPutGoodsFull(addGoodsInfoList.addGoodsList)) {
        uni.showToast({
          title: "请填写完整",
          icon: "none",
          image: "",
          duration: 1500,
          mask: false,
          success: (result) => {},
        });
        return;
      }
      await UpdatePut({
        PutCode: PutCode.value,
        GodownCode: memberStore.GodownCode,
        PutType: data.PutType,
        PutTime: data.PutDate || "",
        PutRemarks: data.PutRemarks || "",
        Operator: memberStore.user_id,
        goods: handleSubmitPutData(addGoodsInfoList.addGoodsList) || [], //物资列表 obj
        goodsx: deleteGoodsList.delCodes || [], //删除物资列表 codes
      });
      toastStore.show = true;
      toastStore.title = "修改成功！";
      toastStore.type = "success";
      //刷新新增物资信息列表
      await getAddGoods({ searchParam: "", pageNum: 1, pageSize: 10 });

      //清空选择项
      selectItemObj.selectItemList = [];
      selectGoodsList.selectGoods = [];
      //清空删除物资列表
      deleteGoodsList.delCodes = [];
    };
    //提交入库单
    const submitPutOrder = async (data: any) => {
      if (isPutGoodsFull(addGoodsInfoList.addGoodsList)) {
        uni.showToast({
          title: "请填写完整",
          icon: "none",
          image: "",
          duration: 1500,
          mask: false,
          success: (result) => {},
        });
        return;
      }
      const res: any = await submitPut({
        Operator: memberStore.user_id,
        PutCode: PutCode.value,
        GodownCode: memberStore.GodownCode,
        PutType: data.PutType,
        PutTime: data.PutDate || "",
        PutRemarks: data.PutRemarks || "",
        goods: handleSubmitPutData(addGoodsInfoList.addGoodsList) || [], //物资列表 obj
        goodsx: deleteGoodsList.delCodes || [], //删除物资列表 codes
      });
      if (res.code == 0) {
        toastStore.show = true;
        toastStore.title = "提交成功！";
        toastStore.type = "success";
        setTimeout(() => {
          uni.navigateBack({
            delta: 1,
          });
        }, 2000);
      }
    };
    //处理提交入库单物资数据
    const handleSubmitPutData = (arr: any) => {
      let result: any = [];
      arr.forEach((obj: any) => {
        let formattedObj = {
          SpecsNumber: obj["SpecsNumber"] || null,
          GoodsCode: obj["GoodsCode"] || null,
          SpecsUnit: obj["SpecsUnit"] || null,
          GoodsBatch: obj["GoodsBatch"] || null,
          Uuid: obj["Uuid"] || null,
          ExpirationDate: obj["ExpirationDate"] || null,
          BoxCode: obj["BoxCode"],
        };
        result.push(formattedObj);
      });
      return result;
    };
    //删除入库单物资
    let delCodes: any = [];
    const deleteGoodsList: any = reactive({ delCodes });
    const deletePutGoods = (data: any) => {
      deleteGoodsList.delCodes.push(data.Uuid);
      const index = addGoodsInfoList.addGoodsList.findIndex(
        (item: any) => item.GoodsCode == data.GoodsCode
      );
      console.log("删除物资", index, addGoodsInfoList.addGoodsList);
      addGoodsInfoList.addGoodsList.splice(index, 1);
    };
    //判断物资是否填写完整
    const isPutGoodsFull = (arr: any) => {
      if (arr.length == 0) {
        return false;
      }
      //判断是否有空值
      const isNull = arr.some((item: any) => {
        return item.BoxCode == "" || item.SpecsNumber == "";
      });

      return isNull;
    };
    // 获取新增物资信息列表
    const getAddGoods = async (data: any) => {
      const res: any = await getAddGoodsList({
        PutCode: PutCode.value,
        searchParam: data.searchParam || "",
        pageNum: data.pageNum || 1,
        pageSize: data.pageSize || 10,
      });
      let arr = res.data.list;
      //去重
      function compareObjects(obj1: any, obj2: any) {
        // 自定义比较两个对象是否相等的逻辑
        // 返回 true 表示相等，返回 false 表示不相等
        // 这里假设对象的属性都是简单类型，没有嵌套对象
        return obj1.Uuid === obj2.Uuid;
      }

      function removeDuplicateObjects(arr: any) {
        return arr.filter((el: any, index: any, self: any) => {
          return (
            index ===
            self.findIndex((obj: any) => {
              return compareObjects(obj, el);
            })
          );
        });
      }

      if (data.searchParam) {
        addGoodsInfoList.addGoodsList = res.data.list;
      } else {
        let oldaarr = JSON.parse(JSON.stringify(addGoodsInfoList.addGoodsList));
        let newarr = [...oldaarr, ...arr];
        addGoodsInfoList.addGoodsList = removeDuplicateObjects(newarr);
      }
      addGoodsInfoList.currPage = res.data.currPage;
      addGoodsInfoList.totalPage = res.data.totalPage;
      console.log("新增物资信息列表", addGoodsInfoList.addGoodsList);
    };
    /*******************************入库单详情************************/
    // 入库单详情
    const putOderDetail: any = reactive({});
    // 获取入库单详情
    const getPutDetailData = async (data: any) => {
      const res: any = await getPutDetail({
        PutCode: data.PutCode,
      });
      Object.assign(putOderDetail, res.data);
      console.log("入库单详情", putOderDetail);
    };
    return {
      addtableHeader,
      goodsTableHeader,
      positionList,
      getPositionListData,
      getGoodsListData,
      goodsListData,
      exist_checked,
      allchecked,
      selectAll,
      selectItem,
      addGoodsInfoList,
      DefiniteMaterial,
      addGoods,
      getAddGoods,
      PutCode,
      addPutOrder,
      addOrdetailOrEdit,
      updatePutOrder,
      submitPutOrder,
      deletePutGoods,
      getPutDetailData,
      putOderDetail,
      clearData,
      putTypeList,
      getGoodsTypeList,
    };
  },
  /**********************************TODO: 持久化***********************/
  {
    // 配置持久化
    persist: {
      // 调整为兼容多端的API
      storage: {
        setItem(key, value) {
          uni.setStorageSync(key, value);
        },
        getItem(key) {
          return uni.getStorageSync(key);
        },
      },
      paths: ["goodsTableHeader", "positionList", "goodsListData"],
    },
  }
);
